<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>服务轮询</title>
    <link href="css/bootstrap.min.css" rel="stylesheet"/>
    <!--bootstrap:一个css框架，主要用来实现一个模式窗口-->
    <style>
        #map {
            position: relative;
            height: 520px;
            border: 1px solid #3473b7;
        }
        #tool {
            position: absolute;
            top: 0px;
            height: 40px;
            width: 200px;
            opacity: 0.6;
            margin-left: -100px;
            left: 50%;
            background-color: #a5c8ec;
            overflow: hidden;
            text-align: center;
            border-bottom-left-radius: 10px;
            border-bottom-right-radius: 10px;
        }

        #tool:hover {
            opacity: 1;
        }
        .modal {
            width: auto;
            max-width: 560px;
            top: 0;
        }
        .modal-body .control-label {
            float: left;
            width: 28%;
            text-align: right;
            margin-top: 5px;
        }
        .modal-body .control-label-add {
            float: left;
            width: 28%;
            text-align: left;
            margin-top: 5px;
        }
        .span7 {
            width: 95%;
        }
        .modal-body input {
            width: 100%;
        }
        .add {
            float: right;
            margin-right: 2%;
        }
        .address {
            display: block;
            float: left;
            width: 50%;
            min-height: 30px;
            margin-left: 2.127659574468085%;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
        }
    </style>
    <script src="js/jquery.js"></script>
    <script src="../libs/SuperMap.Include.js"></script>
    <script>
        var map,layer,
                urls=[];
        var host = document.location.toString().match(/file:\/\//)?"http://127.0.0.1:8090":'http://' + document.location.host;
        var url=host+"/iserver/services/map-world/rest/maps/World", tool, drawPolygon, polygonLayer, drawPolygon;
        var style = {
                strokeColor: "#304DBE",
                strokeWidth: 2,
                pointerEvents: "visiblePainted",
                fillColor: "#304DBE",
                fillOpacity: 0.8
            };
        window.onload=init;

        function init()
        {

            /*设置URL按钮点击事件的响应，即显示模式窗口及背景，并在其中一个显示响应里添加回调函数，以初始化模式窗口里的URL列表*/
            $("#setUrl").click(function(){
                $('#backdrop').show(10,
                        function(){
                            document.getElementById("serverAddr").value="";
                            $("#urlList").empty();
                            for(var i=0;i<urls.length;i++)
                            {
                                initUrlList(urls[i])  ;
                            }
                        }
                );
                $("#myModal").show();
            });

            $("#closeMe, #backdrop,#commit").click(function () {
                $('#backdrop').hide();
                $('#myModal').hide();
            });

            $("#add").click(addURL);
            $("#commit").click(commit);
        }

        function addURL()
        {

            var serverAddr=document.getElementById("serverAddr");
            if(serverAddr.value.match(/http:\/\//)||serverAddr.value.match(/file:\/\//))
            {
                for(var i=0;i<urls.length;i++)
                {
                    if(serverAddr.value==urls[i])
                    {
                        alert("重复添加！")
                        return;
                    }
                }
                initUrlList(serverAddr.value);
                urls.push(serverAddr.value);
            }
            else
            {
                alert("你输入的服务地址格式不正确");
                serverAddr.value="";
            }
        }

        /*往urlList元素里添加一个删除按钮以及一个URL文本*/
        function initUrlList(value)
        {
            var urlList=$("#urlList");
            urlList.append(
                    '<div class="span7"><button style="border-width:0px;margin:0px 5px 0px 0px;padding:0px;width:14px;height:14px;line-height: 10px;font-size: 22px;text-indent: 1px;" ' +
                    'class="btn btn-danger" onclick="deleteURL(event)">-</button>' +'<span>'+value+'</span></div>'
            );
        }

        /*在URL列表里删除一个url*/
        function deleteURL(evt)
        {
            /*移除URL*/
            var parent=evt.target.parentNode;
            parent.parentNode.removeChild(parent);

            /*移除urls里与上面的url文本对应的成员*/
            var len=urls.length;
            for(var i=0;i<len;i++)
            {
                if(urls[i]==parent.childNodes[1].innerHTML)
                {
                    urls.splice(i,1);
                }
            }
        }

        function commit()
        {
            //新建面矢量图层
            polygonLayer = new SuperMap.Layer.Vector("polygonLayer");
            //对面图层应用样式style（前面有定义）
            polygonLayer.style = style;
            /*
             注册featureadded事件,触发drawCompleted()方法
             例如注册"loadstart"事件的单独监听
             events.on({ "loadstart": loadStartListener });
             */
            //创建画面控制，图层是polygonLayer
            drawPolygon = new SuperMap.Control.DrawFeature(polygonLayer, SuperMap.Handler.Polygon);
            drawPolygon.events.on({"featureadded": drawCompleted});
            /*如果地图不存在则新建地图*/
            if (!map) {
                map = new SuperMap.Map("map", {controls: [
                    new SuperMap.Control.ScaleLine(),
                    new SuperMap.Control.Zoom(),
                    new SuperMap.Control.LayerSwitcher(),
                    new SuperMap.Control.Navigation({
                        dragPanOptions: {
                            enableKinetic: true
                        }
                    }), drawPolygon],
                    allOverlays: true
                });
            }
            //定义layer图层，TiledDynamicRESTLayer：分块动态 REST 图层
            layer=new SuperMap.Layer.TiledDynamicRESTLayer("地图", url, {transparent: true}, {useCanvas: true,maxResolution:"auto"});
            /*轮询范例的关键就是urls,当urls包含来自不同主机的同一个地图的rest瓦片地图地址时，所发送的瓦片地图请求将被随机分配给不同的主机，从而加快瓦片地图的访问速度*/

            layer.events.on({"layerInitialized":addLayer});
        }

        function addLayer()
        {
            map.addLayers([layer, polygonLayer]);
            map.setCenter(new SuperMap.LonLat(0,0),1);
        }

        function areaMeasure(){
            clearFeatures();
            drawPolygon.activate();
        }

        //绘完触发事件
        function drawCompleted(drawGeometryArgs) {
            //停止画面控制
            drawPolygon.deactivate();
            //获得图层几何对象
            var geometry = drawGeometryArgs.feature.geometry,
                    measureParam = new SuperMap.REST.MeasureParameters(geometry), /* MeasureParameters：量算参数类。 客户端要量算的地物间的距离或某个区域的面积*/
                    myMeasuerService = new SuperMap.REST.MeasureService(urls, {times: 2}); //量算服务类，该类负责将量算参数传递到服务端，并获取服务端返回的量算结果
            myMeasuerService.events.on({ "processCompleted": measureCompleted ,'processFailed':measureFailed});

            //对MeasureService类型进行判断和赋值，当判断出是LineString时设置MeasureMode.DISTANCE，否则是MeasureMode.AREA

            myMeasuerService.measureMode = SuperMap.REST.MeasureMode.AREA;

            myMeasuerService.processAsync(measureParam); //processAsync负责将客户端的量算参数传递到服务端。
        }

        function  measureFailed(){
            alert('量算失败');
            polygonLayer.removeAllFeatures();
        }

        //测量结束调用事件
        function measureCompleted(measureEventArgs) {
            var   area = measureEventArgs.result.area,
                    unit = measureEventArgs.result.unit;
            alert("量算结果:"+ area + "平方米");
        }
        //移除图层要素
        function clearFeatures(){
            polygonLayer.removeAllFeatures();
        }
    </script>
</head>
<body>
<!--地图容器-->
<div id="map">
</div>
<!--小工具-->
<div id="tool">
    <!--<button id="setUrl" class="btn btn-info">设置URL</button>-->
    <input type="button" class="btn" value="面积量算" onclick="areaMeasure()" />
    <input type="button" class="btn" value="清除" onclick="clearFeatures()" />
</div>

<!--以下为点击添加URL后所弹出的模式窗口，用前端工具bootstrap实现-->
<div id="myModal" class="modal hide fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: block;">
    <div class="modal-header">
        <button type="button" id="closeMe" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 id="myModalLabel">请输入服务地址</h4></div>
    <div class="modal-body">
        <div class="row-fluid">

            <label class="control-label" for="serverAddr">服务地址</label>

            <div class="address">
                <input type="text" id="serverAddr">
            </div>
            <div class="add">
                <button class="btn btn-success" id="add">+</button>
            </div>
        </div>
        <div class="row">
            <div class="span7">
                <p class="muted" style="text-indent: 0;">例如：http://localhost:8090/iserver/services/map-world/rest/maps/World 本范例要求rest world图层服务</p>
            </div>
        </div>
        <div class="row-fluid">
            <label class="control-label-add" for="urlList">已添加地址:</label>
        </div>
        <!--以下为所添加的URL的列表的容器-->
        <div class="row" id="urlList">
        </div>
    </div>
    <div class="modal-footer">
        <button id="commit" class="btn btn-primary">确定</button>
    </div>
</div>
<div id="backdrop" class="modal-backdrop fade in"></div>

</body>
